package com.shu.framework.exception;

import com.shu.framework.enums.CodeMsg;
import com.shu.framework.exception.base.BaseException;
import com.shu.framework.result.Result;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * 拦截所有异常
 */
@ControllerAdvice
@ResponseBody
public class GlobleExceptionHandler {
    @ExceptionHandler(value = Exception.class)
    public Result<String> exceptionHandler(HttpServletRequest request,Exception e){
        if (e instanceof BaseException){
            BaseException ex=(BaseException)e;
            return Result.error(ex.getCodeMsg());
        }
        /**
         * 绑定异常
         */
        if (e instanceof BindException){
            BindException ex=(BindException)e;
            List<ObjectError> allErrors = ex.getAllErrors();

            return Result.error(fillArgs(allErrors.get(0).getDefaultMessage()));
        }
        return Result.error(CodeMsg.SYSTEM_ERROR);

    }
    public CodeMsg fillArgs(Object... args){
        String message=String.format(CodeMsg.SYSTEM_PARAM.msg,args);
        CodeMsg.SYSTEM_PARAM.setMsg(message);
        return CodeMsg.SYSTEM_PARAM;
    }
}
